package alog;

import java.util.*;

/**
 * 排序，双指针
 */
public class threeNUMSUM {
    public static void main(String[] args) {
        int[] num = {1,2,3};
        threeSum(num);
    }
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] > 0)
                break;
            if(i > 0 && nums[i] == nums[i - 1])
                continue;
            int l = i + 1, r = nums.length - 1;
            while (l < r){
                int s = nums[i] + nums[l] + nums[r];
                if(s == 0){
                    List<Integer> p = new ArrayList<>();
                    p.add(nums[i]);
                    p.add(nums[l]);
                    p.add(nums[r]);
                    result.add(p);
                    while(l < r && nums[l] == nums[l + 1])
                        l++;
                    while(l < r && nums[r] == nums[r - 1])
                        r--;
                    l++;
                    r--;
                }
                if (s > 0)
                    r--;
                if (s < 0)
                    l++;
            }
        }
        return result;
    }
}
